import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginApi, logoutApi, getInfoApi } from '@/api/login'

export const useUserStore = defineStore('user', () => {
    const id = ref('')
    const name = ref('')
    const token = ref(getToken())
    const roles = ref([])
    const permissions = ref([])

    // 登录
    const login = (userInfo) => {
        const username = userInfo.username.trim()
        const password = userInfo.password
        return new Promise((resolve, reject) => {
            loginApi(username, password).then(res => {
                setToken(res.token)
                token.value = res.token
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    }

    // 获取用户信息
    const getInfo = () => {
        return new Promise((resolve, reject) => {
            getInfoApi().then(res => {
                const user = res.user
                if (res.roles && res.roles.length > 0) {
                    roles.value = res.roles
                } else {
                    roles.value = ['ROLE_DEFAULT']
                }
                if (res.permissions && res.permissions.length > 0) {
                    permissions.value = res.permissions
                } else {
                    permissions.value = []
                }
                id.value = user.userId
                name.value = user.userName
                resolve(res)
            }).catch(error => {
                reject(error)
            })
        })
    }

    // 退出系统
    const logout = () => {
        return new Promise((resolve, reject) => {
            logoutApi(token.value).then(() => {
                token.value = ''
                roles.value = []
                permissions.value = []
                removeToken()
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    }
    return { id, name, token, roles, permissions, login, getInfo, logout }
}, {
    persist: {
        enabled: true
    }
})
